package net.angrynut.web.model.converter;

import com.google.common.collect.Lists;
import org.springframework.core.convert.converter.Converter;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class StringToDateConverter implements Converter<String, Date> {

    private static final SimpleDateFormat SDF3 = new SimpleDateFormat("yyyy-MM-dd");
    private static final SimpleDateFormat SDF6 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private static final SimpleDateFormat SDF7 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

    private static final List<SimpleDateFormat> SDFS = Lists.newArrayList(SDF3, SDF6, SDF7);

    @Override
    public Date convert(String source) {
        for(SimpleDateFormat sdf : SDFS) {
            Date date = convert(source, sdf);
            if(date != null) return date;
        }
        throw new RuntimeException("把 String 转换为 Date 失败");
    }

    private Date convert(String str, SimpleDateFormat sdf) {
        try {
            return sdf.parse(str);
        } catch (Exception ex) {
            return null;
        }
    }
}
